import { ComponentPublicInstance, getCurrentInstance } from 'vue'
import { createBem } from './bem'

export function createComponentName(name: string) {
  const prefixedName = `zw-${name}`
  return [prefixedName, createBem(prefixedName)] as const
}

export type ComponentInstance = ComponentPublicInstance<{}, any>

export function pick(obj: any, keys: any, ignoreUndefined?: boolean) {
  return keys.reduce((ret: any, key: any) => {
    if (!ignoreUndefined || obj[key] !== undefined) {
      ret[key] = obj[key]
    }
    return ret
  }, {})
}

// 校验数据类型
export const type = (() => {
  const toString = Object.prototype.toString
  const dataType = ['Number', 'String', 'Boolean', 'Array', 'Object', 'Symbol', 'Undefined', 'Null', 'Function', 'Date', 'RegExp', 'Error', 'Promise']
  const type: any = {}
  for (const typeName of dataType) {
    const fnName = `is${typeName}`
    !type[fnName] &&
      (type[fnName] = (value: any) => {
        const checkResult = `[object ${typeName}]`
        return toString.call(value) === checkResult
      })
  }
  type.isNumberic = (n: any) => {
    return !Number.isNaN(parseFloat(n)) && Number.isFinite(Number(n))
  }
  return type
})()

// 暴露 api
export function useExpose(apis: Record<string, any>) {
  const instance = getCurrentInstance()
  if (instance) {
    Object.assign(instance.proxy, apis)
  }
}
